package com.etennis.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.etennis.mapper.*;
import com.etennis.pojos.PageResult;
import com.etennis.pojos.dto.web.MatchDTO;
import com.etennis.pojos.dto.web.MatchDetailQueryDTO;
import com.etennis.pojos.dto.web.MatchPageQueryDTO;
import com.etennis.pojos.entity.*;
import com.etennis.pojos.vo.app.MatchVO;
import com.etennis.pojos.vo.web.EventVO;
import com.etennis.pojos.vo.web.PlayerVO;
import com.etennis.service.IEventsService;
import com.etennis.util.SecurityUtils;
import com.etennis.utils.BeanCopyUtils;
import com.etennis.utils.PageUtil;

import java.util.Objects;
import java.util.Optional;

import com.etennis.utils.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.parameters.P;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class EventsServiceImpl extends ServiceImpl<EventsMapper, Events> implements IEventsService {
    @Autowired
    EventsMapper eventsMapper;
    @Autowired
    RecordMapper recordMapper;
    @Autowired
    MemberMapper memberMapper;
    @Autowired
    SeasonInfoMapper seasonInfoMapper;
    @Autowired
    ClubMapper clubMapper;
    @Autowired
    RedisCache redisCache;

    @Override
    public void saveMatch(MatchDTO matchDTO) {
        Events events = BeanCopyUtils.copyBean(matchDTO, Events.class);
        Long seasonId= redisCache.getCurSeason();
        events.setSeasonId(seasonId);
        // todo eventType
        events.setEventType(String.valueOf(0));
        events.setClubId(SecurityUtils.getLoginClubId());
        eventsMapper.insert(events);

    }


    /**
     *
     * @param matchDetailQueryDTO 日期、选手名称、选手组别
     * @return
     */
    @Override
    public List<EventVO> matchDetail(MatchDetailQueryDTO matchDetailQueryDTO) {

        LambdaQueryWrapper<Member> memberWrapper= Wrappers.lambdaQuery(Member.class)
                .eq(Member::getName,matchDetailQueryDTO.getPlayerName());
        Member member = memberMapper.selectOne(memberWrapper);
        Long playerId= Objects.isNull(member)?null:member.getId();
        List<Record> recordList=recordMapper.matchDetail(playerId,matchDetailQueryDTO);

        // 若找不到符合条件的比赛记录
        if(recordList==null){
            return null;
        }

        List<EventVO> res = recordList.stream().map(each -> {
            EventVO eventVO = BeanCopyUtils.copyBean(each,EventVO.class);
            //选手list
            List<PlayerVO> playersA=new ArrayList<>();
            PlayerVO a1 = getPlayerVOById(each.getWinA1Id());
            PlayerVO a2 = getPlayerVOById(each.getWinA2Id());
            playersA.add(a1);
            playersA.add(a2);

            List<PlayerVO> playersB=new ArrayList<>();
            PlayerVO b1 = getPlayerVOById(each.getLoseB1Id());
            PlayerVO b2 = getPlayerVOById(each.getLoseB2Id());
            playersB.add(b1);
            playersB.add(b2);

            eventVO.setPlayersA(playersA);
            eventVO.setPlayersB(playersB);
            return eventVO;
        }).collect(Collectors.toList());

        return res;
    }

    @Override
    public PageResult<MatchVO> pageMatch(MatchPageQueryDTO matchPageQueryDTO) {
        Page page = PageUtil.convert(matchPageQueryDTO);
        LambdaQueryWrapper<Events> wrapper=new LambdaQueryWrapper<Events>()
                .like(matchPageQueryDTO.getName()!=null,Events::getName,matchPageQueryDTO.getName());
        Page<Events> matchPage=eventsMapper.selectPage(page,wrapper);

        return PageUtil.convert(matchPage,each -> {
            MatchVO matchVO = BeanCopyUtils.copyBean(each, MatchVO.class);
            Club club = clubMapper.selectById(each.getClubId());
            matchVO.setClubName(club.getName());
            return matchVO;
        });

    }

    /**
     * 异常判断暂时设为：只要有属性有空值就返回new PlayerVO()
     * @param id
     * @return
     */
    public PlayerVO getPlayerVOById(Long id){
        if(id==null) return null;

        // todo 选手该场比赛所获积分
        Member member = memberMapper.selectById(id);
        if(member==null) return null;

        Long seasonId=redisCache.getCurSeason();
        LambdaQueryWrapper<Seasoninfo> wrapper = new LambdaQueryWrapper<Seasoninfo>()
                .eq(Seasoninfo::getMemberId, id)
                .eq(Seasoninfo::getSeasonId, seasonId);
        Seasoninfo seasoninfo = seasonInfoMapper.selectOne(wrapper);
        if(seasoninfo==null) return null;

        PlayerVO playerVO = new PlayerVO();
        playerVO.setPlayerId(member.getId());
        playerVO.setPlayerName(member.getName());
        playerVO.setGroupId(seasoninfo.getGroupId());
        playerVO.setScore(member.getScore());

        return playerVO;
    }
}
